package com.lijinquan.tank.abstractfactory;

import com.lijinquan.tank.*;

import java.awt.*;

/**
 * Created by lijinquan on 2020/8/22.
 */
public class RectBullet extends BaseBullet {
    private static final int SPPED = 10;

    private int x, y;
    private Dir dir;

    private boolean living = true;
    private Group group = Group.BAD;

    TankFrame tankFrame = null;

    Rectangle bulRec = new Rectangle();

    public static final int WIDTH = ResourceMgr.bulletU.getWidth(), HEIGHT = ResourceMgr.bulletU.getHeight();

    public RectBullet(int x, int y, Dir dir, Group group, TankFrame tankFrame) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.group = group;
        this.tankFrame = tankFrame;

        bulRec.x = this.x;
        bulRec.y = this.y;
        bulRec.width = WIDTH;
        bulRec.height = HEIGHT;

    }

    @Override
    public void paint(Graphics g) {

        if (!living) {
            return;
        }

        Color color = g.getColor();
        g.setColor(Color.gray);
        g.fillRect(x,y,5,5);
        g.setColor(color);
        move();
    }

    public void move() {

        switch (dir) {
            case LEFT:
                x -= SPPED;
                break;
            case UP:
                y -= SPPED;
                break;
            case DOWN:
                y += SPPED;
                break;
            case RIGHT:
                x += SPPED;
                break;
        }
        if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) {

            this.tankFrame.bullets.remove(this);

        }
        bulRec.x = this.x;
        bulRec.y = this.y;
    }


    @Override
    public void collideWith(Tank tank) {

        if (this.group == tank.getGroup()) return;

        if (this.bulRec.intersects(tank.tankRec)) {
            tank.die();
            this.die();
            tankFrame.explodes.add(tank.tankFrame.gameFactory.createExplode(tank.getX() + this.WIDTH / 2 - Explode.WIDTH / 2, tank.getY() + this.HEIGHT - Explode.HEIGHT / 2, tankFrame));
        }

    }

    private void die() {
        this.living = false;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }
}
